package com.common.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.common.excel.converter.LocalDateExcelConverter;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

public class ExcelExportUtils {

    /**
     * 文件导出
     * 通过网络流下载
     *
     * @param fileName         导出文件名
     * @param templateFilePath 模板路径
     * @param data             导出数据
     * @param response         HttpServletResponse
     */
    public static <T> void exportData(String fileName, String templateFilePath, List<T> data, HttpServletResponse response) {
        try {
            EasyExcel.write(getOutputStream(fileName, response))
                    .withTemplate(templateFilePath)
                    .registerConverter(new LocalDateExcelConverter())
                    .sheet().doFill(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件导出
     * 通过网络流下载
     *
     * @param fileName    导出文件名
     * @param inputStream 读取模板后的流
     * @param data        导出数据
     * @param response    HttpServletResponse
     * @param <T>         泛型对象
     */
    public static <T> void exportData(String fileName, InputStream inputStream, List<T> data, HttpServletResponse response) {
        try {
            EasyExcel.write(getOutputStream(fileName, response))
                    .withTemplate(inputStream)
                    .registerConverter(new LocalDateExcelConverter())
                    .sheet().doFill(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 用于网络下载OutputStream
     *
     * @param fileName 文件名
     * @param response HttpServletResponse
     * @return OutputStream
     * @throws Exception 异常
     */
    public static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setCharacterEncoding("utf8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ExcelTypeEnum.XLSX.getValue());
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "no-store");
            response.addHeader("Cache-Control", "max-age=0");
            return response.getOutputStream();
        } catch (IOException e) {
            throw new Exception("导出excel表格失败!", e);
        }
    }
}
